#!/bin/bash

# Arduino固件编译脚本
# 此脚本用于编译和上传Arduino固件

# 配置参数
SKETCH_NAME="ardunio_firmware"
SKETCH_PATH="ardunio_firmware"
FQBN="arduino:avr:uno"  # Arduino Uno的FQBN
PORT="/dev/ttyUSB0"     # 开发板端口
BUILD_PATH="./build_firmware"

# 从libraries.txt文件加载第三方库依赖列表
LIBRARIES=()
while IFS= read -r line
 do
    # 跳过注释行和空行
    if [[ $line == \#* ]] || [[ -z $line ]]; then
        continue
    fi
    LIBRARIES+=("$line")
done < "$SKETCH_PATH/libraries.txt"

# 检查Arduino CLI是否已安装
if ! command -v arduino-cli &> /dev/null
then
    echo "Arduino CLI未安装，正在安装..."
    # 安装Arduino CLI到当前目录的bin文件夹
    mkdir -p ./bin
    curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | sh -s -- -d ./bin
    # 添加到PATH
    export PATH="./bin:$PATH"
    echo "Arduino CLI安装完成"
fi

# 初始化配置
echo "初始化Arduino CLI配置..."
arduino-cli config init

# 更新配置以生成compile_commands.json
arduino-cli config set build.compile_commands true

# 安装必要的平台核心
echo "安装Arduino AVR平台核心..."
arduino-cli core install arduino:avr

# 安装第三方库依赖
echo "安装第三方库依赖..."
for LIBRARY in "${LIBRARIES[@]}"
do
    echo "安装库: $LIBRARY"
    arduino-cli lib install "$LIBRARY"
    if [ $? -ne 0 ]
    then
        echo "库 $LIBRARY 安装失败，请检查网络连接或库名称是否正确"
        exit 1
    fi
done

# 编译固件
echo "开始编译固件..."
arduino-cli compile --fqbn arduino:avr:uno --build-path ./build $SKETCH_PATH 

# 检查编译是否成功
if [ $? -eq 0 ]
then
    echo "固件编译成功！"
    read -p "是否上传固件到开发板? (y/n): " upload_choice
    if [ "$upload_choice" = "y" ] || [ "$upload_choice" = "Y" ]
    then
        # Linux/WSL需要检查端口权限
        if [ -w $PORT ]
        then
            echo "上传固件到开发板..."
            arduino-cli upload -p $PORT --fqbn $FQBN --input-dir $BUILD_PATH $SKETCH_PATH
        else
            echo "无法访问端口$PORT，尝试提升权限..."
            sudo chmod 666 $PORT
            if [ $? -eq 0 ]
            then
                echo "权限提升成功，重新尝试上传..."
                arduino-cli upload -p $PORT --fqbn $FQBN --input-dir $BUILD_PATH $SKETCH_PATH
            else
                echo "权限提升失败，请以管理员身份运行脚本"
            fi
        fi
        
        if [ $? -eq 0 ]
        then
            echo "固件上传成功！"
        else
            echo "固件上传失败，请检查开发板连接和端口设置"
        fi
    fi
else
    echo "固件编译失败，请检查代码错误"
fi

# 生成compile_commands.json（如果需要）
echo "生成compile_commands.json..."
cp $BUILD_PATH/compile_commands.json .

echo "构建过程完成"